const { config } = require('.');
const mysql = require('mysql2/promise');
const path = require('path');
const fs = require('fs');
const { Sequelize } = require('sequelize');
const modelsDir = path.join(__dirname, 'models');

async function syncSequelizeModels() {
  const sequelize = new Sequelize({
    host: config.host,
    username: config.user,
    password: config.password,
    database: config.database,
    dialect: 'mysql',
    logging: false,
    port: config.port || 3306
  });

  // 批量引入所有模型，并收集模型和defaultData
  const models = [];
  fs.readdirSync(modelsDir).forEach(file => {
    if (file.endsWith('.js')) {
      const modelFactory = require(path.join(modelsDir, file));
      const model = modelFactory(sequelize);
      // 获取 defaultData
      const modelModule = require(path.join(modelsDir, file));
      if (modelModule.defaultData) {
        models.push({ model, defaultData: modelModule.defaultData });
      }
    }
  });

    try {
      await sequelize.sync({ alter: true });
      console.log('所有模型已同步到数据库');
  
      // 清空所有表数据
      for (const { model } of models) {
        await model.destroy({ where: {}, truncate: true, force: true });
      }
      console.log('所有表数据已清空');
  
      // 插入 defaultData
      for (const { model, defaultData } of models) {
        console.log('defaultData ===> ', defaultData);
        if (Array.isArray(defaultData) && defaultData.length > 0) {
          for (const data of defaultData) {
            await model.findOrCreate({ where: data, defaults: data });
          }
        }
      }
      console.log('已插入初始数据');
    } catch (err) {
      console.error('模型同步失败:', err);
    } finally {
      await sequelize.close();
    }
}

async function main() {
  try {
    // 先连接到MySQL（不指定数据库）
    const connection = await mysql.createConnection({
      host: config.host,
      user: config.user,
      password: config.password,
      port: config.port || 3306
    });
    console.log('已连接到 MySQL，准备创建数据库...');

    // 创建数据库
    await connection.query(`CREATE DATABASE IF NOT EXISTS \`${config.database}\``);
    console.log(`数据库 ${config.database} 已创建或已存在`);

    await connection.end();

    // 创建表并插入初始数据
    await syncSequelizeModels();
  } catch (err) {
    console.error('数据库操作失败:', err);
  }
}

main();